package pers.supeijin.devtools.converter.wx2vue.converter.script;

import com.intellij.lang.javascript.psi.JSReferenceExpression;
import com.intellij.lang.javascript.psi.impl.JSChangeUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;

/**
 * 本地引用转换通用工具。
 */
public class LocalJSReferenceConvertUtils {
	/**
	 * 本地属性调用前缀 this.properties.
	 */
	public static final String PROPERTIES_PREFIX = "this.properties.";//小程序属性调用
	/**
	 * 本地数据字段前缀 this.data.
	 */
	public static final String FIELD_PREFIX = "this.data.";
	/**
	 * 当前引用标记
	 */
	public static final String THIS_TAG = "this.";

	private LocalJSReferenceConvertUtils() {
	}

	/**
	 * 转换本地字段（数据调用）  this.data.userName  转换为 this.userName  或者  this.properties.userName  转换为 this.userName
	 * @param psiElement
	 */
	public static void convertFieldsCallExpression(PsiElement psiElement) {
		PsiElement[] collectElements = PsiTreeUtil.collectElements(psiElement, elment -> {
			if (elment instanceof JSReferenceExpression) {
				String elmentText = elment.getText();
				return elmentText.startsWith(FIELD_PREFIX) || elmentText.startsWith(PROPERTIES_PREFIX);
			}
			return false;
		});
		for (PsiElement element : collectElements) {
			JSReferenceExpression jsReferenceExpression = (JSReferenceExpression) element;
			String text = jsReferenceExpression.getText();
			if (text.startsWith(FIELD_PREFIX)) {
				text = text.replace(FIELD_PREFIX, THIS_TAG);
			} else if (text.startsWith(PROPERTIES_PREFIX)) {
				text = text.replace(PROPERTIES_PREFIX, THIS_TAG);
			}
			JSReferenceExpression referenceExpression = JSChangeUtil.createExpressionPsiWithContext(text, jsReferenceExpression, JSReferenceExpression.class);
			PsiElement parent = jsReferenceExpression.getParent();
			parent.addBefore(referenceExpression, jsReferenceExpression);
			jsReferenceExpression.delete();
		}
	}
}
